const express = require('express')
const app = express()
// body-parser
const bodyParser = require('body-parser')
app.use(bodyParser.json())
// db
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost/blog')
const db = mongoose.connection
// model
const Article = require('./models/article.js')
//config
const config = require('./config')
// routers
app.get('/articles', (req, res) => {
  Article.getArticles((err, articles) => {
    if(err) {
      throw err
    }
    res.json(articles)
  })
})
app.get('/articles/:id', (req, res) => {
  Article.getArticleById(req.params.id, (err, article) => {
    if(err) {
      throw err
    }
    res.json(article)
  })
})
app.post('/articles', (req, res) => {
  let article = req.body
  Article.addArticle(article, (err, article) => {
    if(err) {
      throw err
    }
    res.json(article)
  })
})
// listen port
app.listen(config.port)